package com.ibm.psbc.cloud.common.contextcarrier.springmvc;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ibm.psbc.cloud.common.contextcarrier.ContextUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 用于在springmvc rest服务开始前，把头信息变成context
 * @author johnny
 *
 * @param <T> Context的具体类
 */
@ControllerAdvice
@Slf4j
public class Header2ContextAdvice<T>{
	@Inject
	private ContextUtils<T> contextUtils;
    /**
	 * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
	 * 
	 * @param model
	 */
	@ModelAttribute
	public void headerToContext(Model model) {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		log.trace("Service start...");
		HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
		contextUtils.header2Context(request);
	}
}
